<template>
  <div v-loading="editLoading" :class="{'mobile-create': showMobilePage}" class="create-payBack-wrap">
    <explanation :explanation="explanationObj" class="explanation" style="margin: 0;"/>
    <div class="payBack-info">
      <Title title="基础信息" font-size="16px" style="margin: 0 0 16px"/>
      <el-form ref="payBackForm" :rules="rules" :model="paramsObj" :label-position="formAlign" label-width="110px">
        <el-row class="response-el-row">
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="申请人" prop="proposerId">
              <selectWithUserLoad
                ref="proposerRef"
                v-model="paramsObj.proposerObj"
                :default-list="paramsObj.proposerId && paramsObj.proposer?[{id: paramsObj.proposerId, userName: paramsObj.proposer}] : []"
                :multiple="false"
                :value-type="'object'"
                :show-check-user="true"
                key-name="id"
                class="width240"
                label-name="userName"
                filterable
                @change="proposerChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="申请部门" prop="proposerDeptId">
              <el-cascader
                v-model="paramsObj.proposerDeptId"
                :show-all-levels="false"
                :options="deptTreeList"
                :props="{
                  emitPath:false,
                  value: 'id',
                  label: 'name',
                  checkStrictly: true,
                  multiple: false,
                }"
                filterable
                class="width240"
                placeholder="请选择申请部门"
                size="small"
              >
                <template slot-scope="{ data }">
                  <el-tooltip v-if="data.name.length > 14" placement="top-start" effect="dark">
                    <div slot="content" style="max-width: 150px;">{{ data.name }}</div>
                    <span class="inline-tag ellipsisOne">{{ data.name }}</span>
                  </el-tooltip>
                  <span v-else>{{ data.name }}</span>
                </template>
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="所属公司" prop="ourTitle">
              <el-select v-model="paramsObj.ourTitle" placeholder="请选择" clearable filterable class="width240" size="small" popper-class="panel-auto-width">
                <el-option
                  v-for="item in companies"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="还款说明" prop="description">
              <el-input v-model="paramsObj.description" size="small" class="width240" maxlength="500" placeholder="请输入"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="借款欠额(元)" prop="dueAmount">
              <el-input v-model="paramsObj.dueAmount" :disabled="true" type="number" size="small" class="width240" placeholder="该申请人暂无欠款"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="还款金额(元)" prop="backAmount">
              <el-input
                v-model="paramsObj.backAmount"
                size="small"
                class="width240"
                placeholder="请输入"
                oninput="if(value>999999999)value=999999999"
                @input="numInputChange($event, 'backAmount')"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="附件" prop="attachment">
              <upAttachment
                ref="uploadImg"
                :import-api="'/common/file/upload'"
                :hide-confirm="true"
                :is-disabled="false"
                :file-list="paramsObj.attachment"
                :limit="99999"
                btn-text="上传附件"
                @complateSetData="completeSetData"
                @removeFileList="removeFileList"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 关联借款单列表 -->
      <borrowTable
        :list="linkList"
        is-create
        @submit="setLinkList"
        @delOrder="delOrder"
      >
        <PlainCreateBtn
          slot="addBtn"
          size="small"
          @click="addorders">添加</PlainCreateBtn>
      </borrowTable>
    </div>
    <!-- 2.9.7修改成弹窗，修改时流程可以被编辑 -->
    <audit-process
      ref="auditProcess"
      v-model="auditInfo"
      :loading="loading"
      :old-audit-info="oldAuditInfo"
      :flow-structure="processDetail"

      :default-aduitor-list="[paramsObj.proposerObj]"
      :is-modify="Boolean(remodifyId)"
      :disable="Boolean(remodifyId)"
      :is-modify-form="Number(isModifyForm)"
      :current-process-index="Number(currentProcessIndex)"
      @submit="submit"
      @getProcess="getProcess"
    />
    <fixed-pagination>
      <div class="center">
        <el-button v-if="(!reapplyId && !remodifyId) || createNew" type="info" size="small" class="back-btn empty-btn-style" @click="saveDraft">保存草稿</el-button>
        <el-button type="primary" size="small" class="submit-btn" @click="openDrawer">发起审批</el-button>
        <el-button type="info" size="small" class="back-btn cancel-btn-style" @click="toBack">返回</el-button>
      </div>
    </fixed-pagination>
    <!-- 借款单弹窗 -->
    <orderDrawer ref="orderDrawer" :proposer="paramsObj.proposerObj.userName" @submit="setLinkList"/>
  </div>
</template>
<script>
import Title from '@/components/Title';
import AuditProcess from '@/components/Common/auditProcess';
import explanation from '@/components/Common/explanation';
import SelectWithUserLoad from '@/components/Common/selectWithUserLoad';
import upAttachment from '@/components/Common/upAttachment/index';
import borrowTable from '../components/borrowTable';
import orderDrawer from '../components/orderDrawer';
import { showModal } from '@/utils/message';
import { createAuditStructure } from '@/utils/aduitor';
import { mapState } from 'vuex';
import { isContained } from '@/utils/tools';
import processCreate from '@/mixins/processCreate';
import mobileCreate from '@/mixins/mobileCreate';
import { payBackCreate, payBackEdit, payBackInfo, getUsrFinancial, formSubmit } from '@/api/payBack';
import { processManagementDetail } from '@/api/legal';
import { getDepartmentAll } from '@/api/config';
import { getIssueOurTitleList } from '@/api/issueInvoice';
import math from '@/utils/math';

export default {
  components: { Title, AuditProcess, SelectWithUserLoad, explanation, upAttachment, borrowTable, orderDrawer },
  mixins: [processCreate, mobileCreate],
  data() {
    return {
      antiShakeTime: 0, // 防抖时间
      id: '', // 借款申请标识符
      paramsObj: {
        proposerObj: {},
        proposer: '',
        proposerId: '',
        proposerDeptId: '', // 申请人部门
        ourTitle: '', // 所属公司
        description: '', // 还款说明
        attachment: [],
        dueAmount: '', // 欠额
        backAmount: ''// 还款金额
      },
      linkList: [], // 关联借款单
      companies: [], // 所属公司
      deptTreeList: [], // 部门
      remodifyId: null, // 审批修改
      reapplyId: null, // 重新申请
      processDetail: null,
      auditInfo: {// 流程信息
        activeTime: null,
        isSigner: 0,
        countersignSet: 0,
        process: [],
        senders: [],
        id: null
      },
      explanationObj: {
        content: '',
        styConfig: ''
      }, // 审批说明
      rules: {
        proposerId: [{ required: true, trigger: 'change', validator: this.validate('请选择申请人') }],
        proposerDeptId: [{ required: true, trigger: 'change', validator: this.validate('请选择申请部门') }],
        ourTitle: [{ required: true, trigger: 'change', validator: this.validate('请选择所属公司') }],
        description: [{ required: true, trigger: 'blur', validator: this.validate('请输入还款说明') }],
        dueAmount: [{ required: true, trigger: 'blur', validator: this.validate('请选择申请人') }],
        backAmount: [{ required: true, trigger: 'blur', validator: this.validate('请输入还款金额') }]
      },
      loading: false,
      editLoading: false,
      oldAuditInfo: null, // 保存旧流程用于比较，修改的情况需要判断流程是否发生变动
      createNew: 0
    };
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'payBackDetail') {
      to.meta.isDetail = true;
    } else {
      to.meta.isDetail = false;
    }
    next();
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    processStructure() {
      if (!this.processDetail) return [];
      return this.processDetail.process;
    }
  },
  created() {
    this.id = Number(this.$route.params.id) || '';
    this.createNew = Number(this.$route.query.createNew) || 0;
    this.reapplyId = this.$route.query.reapplyId || null;
    this.remodifyId = this.$route.query.remodifyId || null;
    if (this.id) {
      this.getPayBackInfo();
      this.reapplyId && this.getExplanation();
    } else {
      this.initData();
      this.getExplanation();
    }
    this.load();
  },
  methods: {
    validate(msg) {
      return (rule, value, callback) => {
        if (!value && value !== 0) { callback(new Error(msg)); } else { callback(); }
      };
    },
    load() {
      this.queryOurTitleList();
      this.queryDeptTreeList();
    },
    // 表单默认赋值
    initData() {
      this.paramsObj.proposerId = this.userInfo.id;
      this.paramsObj.proposer = this.userInfo.userName;
      this.paramsObj.avatar = this.userInfo.avatar;
      this.paramsObj.proposerObj = {
        id: this.paramsObj.proposerId,
        userName: this.paramsObj.proposer
      };
      if (this.userInfo.deptName && this.userInfo.deptName.length > 0) {
        this.paramsObj.proposerDeptId = this.getFirstDepartment(this.userInfo.departmentAry);
      }
      this.setDueAmount(this.userInfo.id);// 第一次默认申请人为当前用户
    },
    // 获取用户第一个部门的第一个子级部门
    getFirstDepartment() {
      const list = this.userInfo.departmentAry;
      if (Array.isArray(list) && list.length) {
        const ourTitleArr = list[0].id;
        if (Array.isArray(ourTitleArr) && ourTitleArr.length) {
          return ourTitleArr[ourTitleArr.length - 1];
        } else {
          return null;
        }
      } else {
        return null;
      }
    },
    // 我方抬头/所属公司
    queryOurTitleList() {
      getIssueOurTitleList({}).then(res => {
        if (res.code === 200) {
          const result = [];
          res.data.forEach(item => {
            result.push({
              value: item.id,
              label: item.name
            });
          });
          this.companies = result;
        }
      });
    },
    // 设置借款欠额
    setDueAmount(id) {
      getUsrFinancial({ userId: id }).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        this.$set(this.paramsObj, 'dueAmount', Number(res.data.owedAmount / 100).toFixed(2));
      }).catch(err => {
        console.log(err);
      });
    },
    // 获取部门
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    // 信息获取
    getPayBackInfo() {
      this.editLoading = true;
      payBackInfo(this.id).then(res => {
        this.editLoading = false;
        if (res.code !== 200) { this.$message.error(res.message); return; }
        this.linkList = res.data.linkList ? res.data.linkList : [];
        res.data.proposerDeptId = res.data.proposerDepartmentId;// 申请部门
        this.paramsObj = res.data;
        if (this.paramsObj.backAmount || this.paramsObj.backAmount === 0) {
          this.paramsObj.backAmount = math.divide(Number(this.paramsObj.backAmount), 100);
        }
        this.paramsObj.dueAmount = math.divide(Number(this.paramsObj.dueAmount), 100);
        if (this.paramsObj.proposerId) {
          this.setDueAmount(this.paramsObj.proposerId);// 获取最新借款欠额
          this.paramsObj.proposerObj = {
            id: this.paramsObj.proposerId,
            userName: this.paramsObj.proposer
          };
        }
        this.version = Number(res.data.version) || 0;// 当前详情版本，version存在mixins
        if (res.data.auditInfo && !this.reapplyId) { // 流程赋值，保存旧流程用于比较
          this.oldAuditInfo = Object.assign({}, res.data.auditInfo);
          this.auditInfo = JSON.parse(JSON.stringify(res.data.auditInfo));
          this.processDetail = JSON.parse(JSON.stringify(res.data.auditInfo));
        } else {
          this.getExplanation();
        }
      }).catch(err => {
        this.editLoading = false;
        console.log(err);
      });
    },
    // 获取流程详情
    getProcessDetail(isRefresh = false) {
      this.loading = true;
      const data = Object.assign({}, this.paramsObj);
      data.dueAmount = math.multiply(Number(data.dueAmount), 100);
      data.backAmount = math.multiply(Number(data.backAmount), 100);
      data.linkList = this.linkList.map(el => el.id);
      formSubmit(data).then(res => {
        this.loading = false;
        if (res.code === 200) {
          const data = res.data;
          if (this.remodifyId && !isRefresh) {
            this.isProcessChange(data, this.oldAuditInfo) && this.$refs['auditProcess'].setShowRefresh(true);
          } else {
            this.processDetail = data;
            this.auditInfo.activeTime = data.activationTime;
            this.auditInfo.id = data.id;
            // 创建人回填
            const proposer = { id: this.paramsObj.proposerId, userName: this.paramsObj.proposer, avatar: this.paramsObj.avatar };
            this.auditInfo.process = createAuditStructure(data.process, this.userInfo, proposer);
            this.auditInfo.senders = data.senderDiyUserList || [];
          }
          if (this.remodifyId && isRefresh) { // 修改刷新保存刷新后流程用于对比
            this.oldAuditInfo = Object.assign({}, data);
            this.oldAuditInfo.process.forEach(el => {
              this.oldAuditInfo.templateNodeId = el.id;
            });
            this.oldAuditInfo.activeTime = data.activationTime * 1000;
          }
          this.$refs['auditProcess'].openDrawer();
        } else {
          this.$message.error(res.message);
        }
      }).catch(err => {
        this.loading = false;
        console.log(err);
      });
    },
    isProcessChange(nowAuditInfo = {}, oldAuditInfo = {}) {
      if (nowAuditInfo.activationTime !== (oldAuditInfo.activeTime / 1000)) {
        return true;
      }
      const nowProcessIds = nowAuditInfo && nowAuditInfo.process.map(el => el.id) || [];
      const oldProcessIds = oldAuditInfo && oldAuditInfo.process.map(el => el.templateNodeId) || [];
      if (!isContained(nowProcessIds, oldProcessIds)) {
        return true;
      }
      return false;
    },
    getExplanation() { // 获取审批说明
      processManagementDetail({ id: 5404, type: 19 }).then(res => {
        // 审批说明
        const data = res.data[0];
        this.explanationObj.content = data.explanation || '';
        this.explanationObj.styConfig = data.styConfig || '';
      }).catch(err => {
        console.log(err);
      });
    },
    saveDraft() {
      if (!this.id || this.createNew) {
        this.payBackCreate(1, '保存草稿成功');// 1为保存草稿
      } else {
        this.payBackEdit(1);
      }
    },
    getProcess() {
      this.getProcessDetail(true);
      this.isRefresh = true;
    },
    openDrawer() { // 2.9.7 流程弹窗
      this.$refs['payBackForm'].validate(valid => {
        if (valid) { // 表单校验通过，则仅提交表单部分，不提交流程信息，用来获取最新流程
          if (Number(this.paramsObj.backAmount) > Number(this.paramsObj.dueAmount)) { // 限制还款金额不能大于欠款
            this.$message.error('还款金额不能大于借款欠额');
            return;
          }
          if (!this.linkList.length) {
            this.$message.warning('请选择相应的借款单');
            return;
          }
          this.getProcessDetail();
        }
      });
    },
    submit(senders = []) {
      this.modifySenders = senders;// 存到mixins
      if (this.isModifyForm) { // 节点修改走编辑的逻辑
        this.payBackEdit(2);
        return;
      }
      showModal('提交申请后无法进行修改?', '', {
        iconClass: 'del-icon'
      }).then(() => {
        if (!this.id || this.reapplyId) { // 重新提交也是新建
          this.payBackCreate(2, '新建还款申请成功');
        } else {
          this.payBackEdit(2);
        }
      }).catch(() => {
        return false;
      });
    },
    // 限制还款金额
    numInputChange(text, prop) {
      let str = text.replace(/[^\d.]/g, ''); // 只允许数字
      str = str.replace(/\.{2,}/g, '.'); // 连续两个小数点 replace为.
      str = str.replace(/^\./g, '0.'); // 已点为开头 replace为 0.
      str = str.replace(/^(\d*)\.(\d*)\./g, '$1.$2');// 不连续点点 删掉
      str = str.replace(/^0[^\.]+/g, '0'); // 连续多个0 replace为1个0
      str = str.replace(/^(\d+)\.(\d\d).*$/, '$1.$2'); // 只允许保留小数点后3位
      this.paramsObj[prop] = str;
    },
    // 附件逻辑处理
    completeSetData({ data, fileName }) {
      const fileList = {
        name: fileName,
        url: data.url,
        time: new Date().getTime()
      };
      if (typeof data === 'string') {
        fileList.url = data;
      } else {
        fileList.url = data.url;
      }
      this.paramsObj.attachment.push(fileList);
    },
    removeFileList({ file, index }) {
      this.paramsObj.attachment.splice(index, 1);
    },
    proposerChange(data) {
      this.paramsObj.proposerId = data.id;
      this.paramsObj.proposer = data.userName;
      this.paramsObj.avatar = data.avatar;
      this.setDueAmount(data.id);// 设置借款欠额（申请人）
      this.linkList = [];// 切换申请人，清空关联借款单
    },
    // 添加借款单
    addorders() {
      this.$refs['orderDrawer'].openDrawer(this.linkList);
    },
    setLinkList(list = []) {
      this.linkList = list;
    },
    // 删除借款单
    delOrder(index) {
      this.linkList.splice(index, 1);
    },
    formatData() {
      const data = {
        isEditAudit: false,
        ...this.paramsObj
      };
      if (data.backAmount || data.backAmount === 0) {
        data.backAmount = math.multiply(Number(data.backAmount), 100);
      }
      // 金额转成分
      data.dueAmount = math.multiply(Number(data.dueAmount), 100);
      data.linkList = this.linkList.map(el => el.id);
      data.auditInfo = JSON.parse(JSON.stringify(this.auditInfo));
      if (this.createNew) {
        delete data.id;
      }
      return data;
    },
    payBackEdit(submitType) { // 1草稿编辑 2为详情编辑
      const data = this.formatData();
      data.submitType = submitType;
      if (this.remodifyId && this.isRefresh) {
        data.isEditAudit = true;// 修改时，流程被编辑或者更新
      }
      this.handleModifyData(data);
      payBackEdit(this.id, data).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.message);
        }
        if (res.data.id && res.data.processId) {
          this.$router.push({
            name: 'payBackDetail',
            query: {
              id: res.data.id,
              processId: res.data.processId
            }
          });
        } else {
          this.$router.push({
            name: 'payBack'
          });
        }
      }).catch(err => {
        if (err.code === 505) { // 节点修改跳转详情
          this.nodeModifyJumpDetail({ routeName: 'payBackDetail', params: {}, query: { id: this.id, processId: this.remodifyId }});
        }
        this.dealError(err);
      });
    },
    payBackCreate(submitType, message) { // 1草稿 2为保存提交 3重新申请
      var timestamp = Date.parse(new Date());
      if (timestamp - this.antiShakeTime < 500) {
        return;
      }
      this.antiShakeTime = timestamp;
      const data = this.formatData();
      data.submitType = submitType;
      payBackCreate(data).then(res => {
        if (res.code !== 200) { this.$message.error(res.message); return; }
        this.$message.success(message);
        if (submitType === 2) {
          this.$router.push({
            name: 'payBackDetail',
            query: {
              id: res.data.id,
              processId: res.data.processId
            }
          });
          return;
        } else {
          this.$router.push({
            name: 'payBack'
          });
        }
      }).catch(err => {
        this.dealError(err);
      });
    },
    dealError(err) { // 处理异常code
      console.log(err);
      if (err.code === 502 && !this.remodifyId) { // 流程变更
        this.$refs['auditProcess'].setShowRefresh(true);
      }
      if (err.code === 508) { // 借款欠额变动
        this.setDueAmount(this.paramsObj.proposerId);// 获取最新欠额
      }
    },
    toBack() {
      if (this.remodifyId) {
        this.processId = this.remodifyId;
      }
      if (this.reapplyId) {
        this.processId = this.reapplyId;
      }
      if (this.$route.meta.isDetail) {
        this.$router.push({
          name: 'payBackDetail',
          query: {
            id: this.id,
            processId: this.processId
          }
        });
        return;
      }
      this.$router.push({
        name: 'payBack'
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.create-payBack-wrap{
	margin: 16px;
	background: #FFFFFF;
	min-height: calc(100vh - 56px);
  .width240 {
    width: 240px;
  }
  .payBack-info{
    padding: 20px 24px 24px;
  }
  .empty-btn-style {
    border-color: #406EFF;
    background: #fff;
    color: #406EFF;
    width: 80px;
    padding: 7px 0;
    text-align: center;
  }
  .explanation{
    padding-left: 9px;
  }
}
</style>
